package org.kfish.framework.helper;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.kfish.framework.log.Log;
import org.kfish.framework.log.Log.LogType;

/**
 * 与Servlet API 解耦（保证线程安全，其他地方想使用request、response 直接通过该helper获得）
 * @author CK
 *
 */
public class ServletHelper {

	//线程隔离的变量
	private static final ThreadLocal<ServletHelper> SERVLET_HELPER_HOLDER = new ThreadLocal<>();
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	private ServletHelper(HttpServletRequest request,HttpServletResponse response){
		this.request  = request;
		this.response = response;
	}
	
	public static void init (HttpServletRequest request,HttpServletResponse response){
		SERVLET_HELPER_HOLDER.set(new ServletHelper(request, response));
	}
	
	public static void destroy(){
		SERVLET_HELPER_HOLDER.remove();
	}
	
	public static HttpServletRequest getRequest(){
		return SERVLET_HELPER_HOLDER.get().request;
	}
	
	public static HttpServletResponse getResponse(){
		return SERVLET_HELPER_HOLDER.get().response;
	}
	
	public static HttpSession getSession(){
		return getRequest().getSession();
	}
	
	public static ServletContext getServletContext(){
		return getRequest().getServletContext();
	}
	
	public static void setRequestAttribute(String key,Object value){
		getRequest().setAttribute(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getRequestAttribute(String key){
		
		return (T) getRequest().getAttribute(key);
	}
	
	public static void removeRequestAttribute(String key){
		getRequest().removeAttribute(key);
	}
	
	public static void sendRedirect(String location){
		try {
			getResponse().sendRedirect(location);
		} catch (IOException e) {
			Log.getLogger(LogType.DETAIL).error("redirect failure",e);
		}
	}
	
	public static void setSessionAttribute(String key,Object value){
		getSession().setAttribute(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(String key){
		return (T) getSession().getAttribute(key);
	}
	
	public static void removeSessionAttrbute(String key){
		getSession().removeAttribute(key);
	}
	
	public static void invalidateSession(){
		
		getSession().invalidate();
	}
	
	
	
	
	
	
	
	
}
